package com.example.service;

import com.example.dao.UserDao;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserService {

    @Resource
    private UserDao userDao;

    public void save(User user) {
        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        user.setCreateTime(now);
        userDao.save(user);
    }

    //包含了新增和更新的功能，区别在于有没有传ID
    public void add(User user) {
        userDao.save(user);
    }

    //删除
    public void del(Long id){
        userDao.deleteById(id);
    }

    public List<User> findAll() {
        return userDao.findAll();
    }

    //根据id查询用户
    public User findById(Long id){
        return userDao.findById(id).orElse(null);
    }

    //分页查询用户
    public Page<User> findPage(Integer pageNum, Integer pageSize, String name) {
        // 构建分页查询条件
        Sort sort = new Sort(Sort.Direction.DESC, "create_time");
        Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
        return userDao.findByNameLike(name, pageRequest);
    }


    //jojo
//    @Autowired
//    private UserDao userDao;
//
//    public void save(User user) {
//        String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        user.setCreateTime(now);
//        userDao.save(user);
//    }
//
//    public void delete() {
//        userDao.deleteById(id);
//    }
//
//    public User findById() {
//        return userDao.findById(id).orElse(null);
//    }
//
//    public List<User> findAll() {
//        return userDao.findAll();
//    }
//
//    public Page<User> findPage(Integer pageNum, Integer pageSize, String name) {
//        // 构建分页查询条件
//        Sort sort = new Sort(Sort.Direction.DESC, "create_time");
//        Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
//        return userDao.findByNameLike(name, pageRequest);
//    }
}
